package qky.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import qky.api.entity.TokenEntity;

import java.util.Date;
import java.util.UUID;


@Service("tokenService")
public class TokenServiceImpl extends TokenServiceImplGen {

    /**
     * 12小时后过期
     */
    private final static int EXPIRE = 3600 * 12;

    @Override
    public TokenEntity queryByToken(String token) {
        return this.dao.getByToken(token);
    }

    @Override
    public void expireToken(String userId){
        Date now = new Date();

        TokenEntity tokenEntity = new TokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setUpdateTime(now);
        tokenEntity.setExpireTime(now);
        this.update(tokenEntity);
    }

    private String generateToken(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    public TokenEntity createToken(String userId) {
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //生成token
        String token = generateToken();

        //保存或更新用户token
        TokenEntity entity = this.dao.selectById(userId);
        if (entity == null) {
            entity = new TokenEntity();
            entity.setUserId(userId);
            entity.setToken(token);
            entity.setUpdateTime(now);
            entity.setExpireTime(expireTime);
            entity.setDeleted(0);
            this.save(entity);
        } else {
            entity.setToken(token);
            entity.setUpdateTime(now);
            entity.setExpireTime(expireTime);
            entity.setDeleted(0);
            this.update(entity);
        }

        return entity;
    }
}
